Push To Two Git Repos At Once
Back in 2012, I had experienced a situation where one of my Git repositories (I will not mention any specific providers here) suddenly disappeared overnight, with no recovery options. And while I was able to restore some of the code from local backups, it was an all-around bad position to be in. You know how you’re always told to not put all the eggs in one basket? Who knew that it applies to code as well!
As it turns out, Git has some nifty capabilities that allow me to reduce the likelihood of losing my code. But to start, I needed to decide where I want to store the swaths of code I had been playing with. For me, the primary location is always GitHub. But there are also other code hosting services that I could use, such as:
While other cloud-based options are great, I wanted to experiment and set up a local set of repositories, on another machine that I have within my household, that acts as the server. The easiest way to do that was through GitLab’s open-source community edition of their software. With it, I can easily deploy a GitLab instance in whichever way is most convenient for the target environment - it is possible to even run it on a custom cloud account.
I chose to use the Docker-based approach - all I needed to do is install Docker on my machine and then provision the image. I am all about having things work out-of-the-box and GitLab excels here - I had to perform minimal configuration to get it working. Took me at most 10 minutes to get this working:
All I needed to do now is configure two additional remotes to which I can push. To start, I can just edit the .git/config
file, and add another pushurl
for the existing remote:
[remote "origin"]
url = https://github.com/USER/REPOSITORY.git
fetch = +refs/heads/*:refs/remotes/origin/*
pushurl = https://oauth2:MY_GITLAB_KEY@MY_GITLAB_URL/USER/REPOSITORY.git
pushurl = https://github.com/USER/REPOSITORY.git
I should mention that including the key in the config is not the best idea, but it does work for quick and dirty experimentation. The OAuth access token can be obtained in the GitLab instance settings, located at https://GITLAB_URL/profile/personal_access_tokens
.
Alternatively, I could add the pushurl
parameter with the help of git
in the Terminal:
git remote set-url --add --push origin https://oauth2:MY_GITLAB_KEY@MY_GITLAB_URL/USER/REPOSITORY.git
That’s it! It’s now possible to push the same repository to two different locations at once, ensuring that the code is mirrored. You don’t even need to do this with GitLab - it will work with any other Git repository.
PS: The beauty of the local GitLab approach is that it can also run on a Synology NAS.